<%--                                                                       --%>
<%-- Copyright (c) 2005 BroadVision, Inc.  All rights reserved.            --%>
<%--                                                                       --%>
<%-- This software is copyrighted. Under the copyright laws, this software --%>
<%-- may not be copied, in whole or in part, without prior written consent --%>
<%-- of BroadVision, Inc. or its assignees. This software is provided      --%>
<%-- under the terms of a license between BroadVision and the recipient,   --%>
<%-- and its use is subject to the terms of that license.                  --%>
<%--                                                                       --%>
<%-- This software may be protected by one or more U.S. and International  --%>
<%-- patents.  Certain applications of BroadVision One-To-One software are --%>
<%-- covered by U.S. patent 5,710,887.                                     --%>
<%--                                                                       --%>
<%-- TRADEMARKS: BroadVision and BroadVision One-To-One are registered     --%>
<%-- trademarks of BroadVision, Inc., in the United States and the         --%>
<%-- European Community, and are trademarks of BroadVision, Inc., in other --%>
<%-- countries.  The BroadVision logo, is a trademark of BroadVision,      --%>
<%-- Inc., in the United States and other countries. Additionally, IONA    --%>
<%-- and Orbix are trademarks of IONA Technologies, Ltd.  RSA, MD5, and    --%>
<%-- RC2 are trademarks of RSA Data Security, Inc.                         --%>
<%--                                                                       --%>

<%-- This page expects the following parameter in request                  --%>
<%--    contentTypeId                                                      --%>
<%--    visitorId                                                          --%>
<%--    serviceId                                                          --%>
<%--    maxFind                                                            --%>
<%--    selectedOID                                                        --%>
<%--    selectedName                                                       --%>
<%--    catOID                                                             --%>

<%@include file="/cs/common/charset.jsp" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Iterator" %>
<%@ page import="java.util.ListIterator" %>

<%@ page import="com.broadvision.data.client.DataManager" %>
<%@ page import="com.broadvision.data.client.Content" %>
<%@ page import="com.broadvision.data.common.ContentUID" %>
<%@ page import="com.broadvision.data.common.ContentKey" %>
<%@ page import="com.broadvision.data.client.Category" %>
<%@ page import="com.broadvision.data.common.DataConstants" %>
<%@ page import="com.broadvision.ssp.util.TableConstants" %>
<%@ page import="com.broadvision.web.servlet.SessionVisitor" %>

<%@ page import="com.broadvision.system.accesscontrol.client.AccessManager" %>
<%@ page import="com.broadvision.visitor.client.Visitor" %>

<%@ page import="javax.servlet.http.HttpSession" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="com.broadvision.portal.foundation.action.browse.BrowseActionUtil" %>
<%@ page import="com.broadvision.portal.services.PortalContent" %>




<%@ taglib uri="/WEB-INF/webflow.tld" prefix="webflow" %>
<%@ taglib uri="/WEB-INF/webform.tld" prefix="webform" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%!
  /*
   * used to get the full path to the current category
   *  Eg: /Editorials/Business Operations/Contacts
   *  
   * returns : java.util.ArrayList each element of the list is an
   *           array that contains two strings
   *       0 : "JavaScript:onChangeCategory(<categoryId>)"
   *       1 : Category Name
   *
   * NOTE: The List is in reverse order
   *
   * the name of the root category is appended to the end of list
   *   Eg: Editorials (equivalent to "/")
   *
   * All exceptions are propagated to caller
   */
  public static List getCategoryPath(Category curCat, int contentTypeId, DataManager dataMgr ) throws Exception {
  
    List resultList = new ArrayList();
  
    if (curCat != null) {
      Category category = curCat;
      while (category != null) {
        String categoryName = category.getStringValue(TableConstants.NAME);
        long categoryId = category.getOid();

        // Create list of array[name, oid] .
        String[] nameIdPair = new String[2];
        //nameIdPair[0] = "JavaScript:onChangeCategory(" + String.valueOf(categoryId) + ")";
        nameIdPair[0] = String.valueOf(categoryId) ;
        nameIdPair[1] = categoryName;
      
        resultList.add(nameIdPair); 
        category = category.getParent();  
      }
    }

    // Top level category, display the content type name here 
    String cntTypeName = DataManager.getContentTypeName(contentTypeId);
    String[] nameIdPair = new String[2];
    nameIdPair[0] = "0";
    nameIdPair[1] = cntTypeName;
    resultList.add(nameIdPair); 
    
    return resultList;
  }

  /* 
   * used to get a list of all the categories under the current category
   * There is no limit on the number of categories shown
   *
   * returns : java.util.List each element of the list is an
   *           array that contains two strings
   *       0 : categoryId
   *       1 : Category Name
   *
   * If current category is root category, the also append "unclassified" to 
   * the end of the list with no URL link
   *
   * All exceptions are propagated to caller
   */
  public static List getChildrenList(Category curCat, int serviceId, 
  								int contentTypeId, DataManager dataMgr) 
         throws Exception {
  
    List resultList = new ArrayList();

    // Get the child categories for this category. 
    List catList = null;
    if (curCat == null ) {
      catList = dataMgr.getTopCategories(DataConstants.DEFAULT_CATEGORY_TYPE_ID,
       								     serviceId, contentTypeId);
    }
    else {
      catList = curCat.getChildren();
    }

    // iterate through the list of child categories and create a list of array
    // [name][URL link]
    Iterator iter = catList.iterator();
    while(iter.hasNext()) {
      Category childCategory = (Category)iter.next();

      String categoryName = childCategory.getStringValue(TableConstants.NAME);
      String catOid = String.valueOf(childCategory.getOid());
      String oidLink = catOid;
      
      String[] nameIdPair = new String[2];
      nameIdPair[0] = oidLink;
      nameIdPair[1] = categoryName;
      
      resultList.add(nameIdPair); 
    }
   
    return resultList;
  }  

  /* 
   * used to get a list of all content under the selected category
   * The data returned is limited by maxFind
   *
   * returns : java.util.List each element of the list is an
   *           array that contains two strings
   *       0 : <a href="JavaScript:onChangeCategory(<categoryId)>"
   *       1 : Category Name
   *
   * All exceptions are propagated to caller
   */
  public static List getChildContentList(HttpServletRequest request, Category curCat, int contentTypeId, 
					int maxFind, int serviceId, Visitor visitor, DataManager dataMgr, boolean isAdminApp) 
       throws Exception {
  
    List resultList = new ArrayList();

    dataMgr.getCallSettings().setMaxReturn(maxFind);

    
	// If content admin, then ignore qualfiers and ACL
	// so set interestedConstentStatus to BV_ALL_DB_CONTENT
    
    AccessManager accessMgr = AccessManager.instance();

	if( isAdminApp ) {
	   dataMgr.getCallSettings().setInterestedContentStatus(DataConstants.BV_ALL_DB_CONTENT);
	   dataMgr.getCallSettings().setFilteringFlag(false);
	   if( null != curCat) {
	   	 curCat.getCallSettings().setFilteringFlag(false);
	   }
	}

    // If the category is unclassified category
    // Get the content list under it
    
    long[] contentIdsArray = new long[maxFind];
    if ( null == curCat ) {
      contentIdsArray = dataMgr.getUnclassifiedMemberIds(DataConstants.DEFAULT_CATEGORY_TYPE_ID, serviceId, contentTypeId);
    }
    else {
      contentIdsArray = curCat.getMemberIds(contentTypeId, false);  
    }
    
    // get the content item for the ids
    List contentList = dataMgr.getContents(contentTypeId, serviceId, contentIdsArray);
	
	//get the content display column
	//String displayColumn = BrowseActionUtil.getContentKey(request, contentTypeId);
	String displayColumn = PortalContent.getContentDisplayName(contentTypeId);
    Iterator iter = contentList.iterator();
    while(iter.hasNext() ) {
      Content cnt = (Content)iter.next();
      boolean bPermitted = true;
      if( !isAdminApp ) {
        bPermitted = accessMgr.isPermitted(visitor, cnt, "ViewContent");
      }
      
      if( bPermitted) {
        String[] nameIdPair = new String[2];
        nameIdPair[0] = String.valueOf(cnt.getOid());
        //nameIdPair[1] = cnt.getStringValue("ED_NAME");
        //ContentKey contentKey = cnt.getKey();
		//nameIdPair[1] = (contentKey.getKey()).toString();
		String contentDisplayName = cnt.getStringValue(displayColumn);
		//if the content display name is null or empty, we use default key instead of it.
        if (contentDisplayName== null || contentDisplayName.equals("")){
        	ContentKey contentKey = cnt.getKey();
			nameIdPair[1] = (contentKey.getKey()).toString();
        }else{
			nameIdPair[1] = contentDisplayName;
		}
      
        resultList.add(nameIdPair);
      }
    }
    return resultList;
  }
  
  /** 
   * Takes a string value as input and escapes all single quote characters.
   */
  public static String fixSingleQuote(String str) {
    return replace(str, "'","\\\'");
  }
  
  static String replace(String s, String one, String another) {
  // In a string replace one substring with another
    if (s.equals("")) return "";
    String res = "";
    int i = s.indexOf(one,0);
    int lastpos = 0;
    while (i != -1) {
      res += s.substring(lastpos,i) + another;
      lastpos = i + one.length();
      i = s.indexOf(one,lastpos);
    }
    res += s.substring(lastpos);  // the rest
    return res;  
  }

%>

<%  
  // Get the content type Id to browse
  String contentTypeStr = request.getParameter("relatedCnt");
  if (contentTypeStr == null || contentTypeStr.equals("") ) {
    %>
      Error: ContentType is expected but was not passed in.  
    <%
    return;
  }
  int contentTypeId = Integer.parseInt(contentTypeStr);
  
  // Get the visitorId
  String visitorIdStr = request.getParameter("VisitorId");
  if( visitorIdStr == null || visitorIdStr.equals("") ) {
    %>
      Error: VisitorId is expected but was not passed in.  
    <%
    return;
  }
  long visitorId = Long.parseLong(visitorIdStr);
  
  // Get the serviceId
  String serviceIdStr = request.getParameter("ServiceId");
  if( serviceIdStr == null || serviceIdStr.equals("") ) {
    %>
      Error: serviceId is expected but was not passed in.  
    <%
    return;
  }
  int serviceId = Integer.parseInt(serviceIdStr);

  // Maximum number of content to display in a category 
  String maxFindStr = request.getParameter("maxFind");
  int maxFind = 50;
  if( maxFindStr != null && !maxFindStr.equals("") )  {
    maxFind = Integer.parseInt(maxFindStr);
  }
  //System.out.println("maxFind= " + maxFind);

  String selectedOID = request.getParameter("selectedOID");
  String selectedName = request.getParameter("selectedName");

  // Initialize DataManager as it will be used everywhere
  DataManager dataMgr = new DataManager(visitorId);
  
  // Get category OID. 
  // If provided, then start Browse from this location
  // Else, start from the root category
  String catOID = request.getParameter("catOID");
  if(catOID == null) {
    catOID = String.valueOf(DataConstants.BV_UNCLASSIFIED_OID);
  }
  Category curCat = null;
  String cntTypeName = DataManager.getContentTypeName(contentTypeId);
  if (catOID == null || catOID.equals("") || catOID.equals("0") || catOID.equals(String.valueOf(DataConstants.BV_UNCLASSIFIED_OID))) {
    curCat = null; 
  }
  else {
    ContentUID catUid = new ContentUID(DataConstants.DEFAULT_CATEGORY_TYPE_ID, serviceId, Integer.parseInt(catOID), cntTypeName);

    curCat = dataMgr.getCategory(catUid);  
  }

  // Invoke the functions defined to get the data
  List categoryPathList = null ;
  try {
    categoryPathList = getCategoryPath(curCat, contentTypeId, dataMgr);
  }
  catch(Exception e){
    e.printStackTrace();
    %>Error getting category information<%
    return;
  }
  
  List childrenList = null;
  try {
    childrenList = getChildrenList(curCat, serviceId, contentTypeId, dataMgr);
  }
  catch(Exception e){
    e.printStackTrace();
    %>Error getting category information<%
    return;
  }

  List childContentList  = null;
  SessionVisitor sessionVisitor = SessionVisitor.getInstance(request.getSession());

  try {
  
    String cxtPath = request.getContextPath() ;
    boolean isAdminApp = false;
    if( cxtPath.equals("/bvmc") ) {
       isAdminApp = true;
    }
    childContentList = getChildContentList(request, curCat, contentTypeId, maxFind, serviceId, sessionVisitor.getVisitor(), dataMgr, isAdminApp);
  }
  catch(Exception e){
    e.printStackTrace();
    %>Error getting category information<%
    return;
  }  
  
  String unclassifiedLabel="Unclassified";
  String tmpThisPage = request.getContextPath() + "/ep/portalPublish/itemPicker.jsp";
  String thisPage = response.encodeRedirectURL(tmpThisPage);
  
  String styleLink = "";
  if (request.getContextPath().equals("/bvmc")) { 
    styleLink = request.getContextPath() + "/mc/css/global.css";
  }
  else {
    styleLink = request.getContextPath() + "/ep/css/globalc3.css"; 	
  }

%>

<html>
  <head>
	<title>Find Related Content</title>
    <link rel="stylesheet" type="text/css" href="<%=styleLink%>">

    
    <script language="JavaScript">
	  function onChangePage(page)
	  {
		document.itempicker.pageNum.value = page;
		document.itempicker.submit();
	  }
	
	  function onSelect(OID , name)
	  {
	    document.itempicker.selectedOID.value = OID;
	    document.itempicker.selectedName.value = name;
	  }
	
	  function onSave()
	  {
	    var OID = document.itempicker.selectedOID.value;
	    var name = document.itempicker.selectedName.value;
	
	    var temp = "";
	
	    if (name == "null" || name == null || name == '') {
	      alert('<bean:message key="cm.content.selectItem"/>');
	      return;
	    }
	    //remove + sign
	    for(i=0; i<name.length; i++)
	      {
		var c = name.charAt(i);
		if(c == '+')
		  temp += ' ';
		else
		  temp += c;
	      }
	
	    var decodeName = unescape(temp);
	    window.opener.setRelatedContent(OID, decodeName);    
	    window.close();
	  }
	
      function checkNonNegativeIntegerLexical(s){
        if (!checkPattern(s, "\\d+")){
          return false;
        }// if
        return true;
      }

      // functions for pattern checking
      function checkPattern(s, p){
        var regExp = new RegExp(p, "g");
        var result = s.match(regExp);
        if (result != null){
          for(i = 0; i < result.length; i++){
            if (result[i] == s){
              return true;
            }
          }
        }
        return false;
      }


	  function isPositiveInteger(s){
        if ( (s == null) || (s.length == 0) ) {
          return false;
        }  
        if (!checkPattern(s, "\\d+")) {
		  return false;
        }
        
        if ( s < 1 ) {
          return false;
        }
        return true;          
	  }


	  function onMaxFind()
	  {
	    if ( !isPositiveInteger(document.itempicker.maxFindControl.value) ) {
alert("<bean:message  key="enter.valid.positive.integer"/>");
	      return false;
	    }
	    document.itempicker.maxFind.value = document.itempicker.maxFindControl.value;
	    document.itempicker.submit();
	  }
	
	  function onChangeCategory(OID)
	  {
	    document.itempicker.catOID.value = OID;
	    document.itempicker.submit();
	  }
	
	</script>
  </head>

  <body>

    <webflow:encode url="<%=thisPage%>" id="popupURL" />
    <% String popup = (String)pageContext.getAttribute("popupURL"); %>

    <form name="itempicker" action="<%=popup%>" method=POST >

      <input type="hidden" name= "relatedCnt" value= "<%=contentTypeId%>">
      <input type="hidden" name= "VisitorId" value= "<%=visitorId%>">
      <input type="hidden" name= "ServiceId" value= "<%=serviceId%>">
      <input type="hidden" name= "catOID" value= "<%=catOID%>">
      <input type="hidden" name= "selectedOID" value= "<%=selectedOID%>">
      <input type="hidden" name= "selectedName" value= "<%=selectedName%>">
      <input type="hidden" name= "maxFind" value= "<%=maxFind%>">

			
			<table class="zoneFive" width="100%" cellspacing="0" cellpadding="0" border="0" summary="Main body">
        <tr>
          <td valign="top">
	          <div class="pageTitle"><bean:message bundle="appCommonRes" key="ep.browse.cat"/></div>

	          <div class="blockTitle">
				      <span class="left">&nbsp;</span>
					    <span class="right">&nbsp;</span>
				    </div>
				    <div class="blockWrap">
            <div class="pageInstructions">
            <bean:message bundle="appCommonRes" key="ep.browse.desc"/>

            </div>
		<table class="labelForm" width="100%" cellspacing="0" cellpadding="2" summary="Form fields">
		  <tr>
		    <td width="20%" nowrap align="left" class="label">
		    <bean:message bundle="appCommonRes" key="ep.max.item"/>:

                    </td>
                    <td valign="top" width="80%" class="labelField" nowrap> 
                      <input type="text" size="3" maxlength="4" name="maxFindControl" value="<%=maxFind%>">
                      <input type="submit" name="showResults" class="pageButton" 
 value="<bean:message bundle="appCommonRes" key="ep.show.reullts"/>" onClick="javascript:onMaxFind()"/>
                    </td>
		
                  </tr>
		</table>
		
               <div class="breadcrumb">		
								 
                <b><bean:message bundle="appCommonRes" key="ep.cat.path"/>:</b>&nbsp;
                <%
                ListIterator iter = categoryPathList.listIterator(categoryPathList.size());
                while( iter.hasPrevious()) {
                  String[] nameValPair = (String[])(iter.previous());
                %>
                /<a href="JavaScript:onChangeCategory(<%=nameValPair[0]%>)" >
<%if((nameValPair[1].toString()).equals("EDITORIAL")){%>
<bean:message key="key.editorial"/>
<%}else{%>

                <%=nameValPair[1]%>
<%}%>
                 </a>
                <%
                }
                %>
                             
            </div>  
 
            <table class="labelForm" width="100%" border="0" cellspacing="0" cellpadding="0">
            <%
             if( childrenList.size() <= 0 ) {
            %>
              <tr>
		<td class="labelField" align="center" colspan="2"> 
<bean:message  key="no.cat.found"/>
                <td>
							</tr>	
            <%  
             }
             else {
               Iterator iterChildren = childrenList.iterator();
               while(iterChildren.hasNext()) {
               String[] nameValPair = (String[])(iterChildren.next());
            %>
             <tr> 
               <td nowrap width="10%" class="labelField" align="right">
                 <img src="/portal/ep/images/icons/icon_channel.gif" 
                 width="22" height="18" alt="Category" title="Channel icon" border="0" align="absmiddle">
               </td>
               <td width="90%" class="labelField">
                 <a href="JavaScript:onChangeCategory(<%=nameValPair[0]%>)" >
                 <%=nameValPair[1]%>
                 </a>
               </td>
             </tr>
            <%
            }  
          }
            if( catOID.equals(String.valueOf(DataConstants.BV_UNCLASSIFIED_OID))) {
            %>
            <tr>
              <td nowrap width="10%" class="labelField" align="right">
                 <img src="/portal/ep/images/icons/icon_channel.gif" 
                 width="22" height="18" alt="Category" title="Channel icon" border="0" align="absmiddle">
              </td>
              <td width="90%" class="labelField">
<%if((unclassifiedLabel.toString()).equals("Unclassified")){%>
<bean:message key="key.unclassified"/>
<%}else{%>
               <%=unclassifiedLabel%>
<%}%>
               </a>
              </td>
            </tr>
            <%
           }
          %>
          </table>
      
      <br>
      
			<%
	    int numContent = childContentList.size();
	    String checkedStr = " CHECKED";
	    String emptyStr = "";
	    %>
      
	    <div class="pageSubsubtitle"><bean:message bundle="appCommonRes" key="ep.select.results"/>&nbsp;-&nbsp;<%= numContent%> <bean:message bundle="appCommonRes" key="ep.items"/> <bean:message bundle="appCommonRes" key="ep.found"/></div>
	    
      <table class="dataTable" width="100%" border="0" cellspacing="1" cellpadding="2">
        <tr class="listHeader"> 
          <th id="select" width="10%" align="center" nowrap>  
            <bean:message bundle="appCommonRes" key="ep.select"/>
          </th>
	        <th id="Name" width="90%" align="left">
	          <bean:message bundle="appCommonRes" key="ep.item.name"/>
	        </th>
	      </tr>
	  
	    <%       
	    Iterator iterContent = childContentList.iterator();
	    String checkFlag = emptyStr;
	    String listID="listOdd";
	    int i=0;
	    while(iterContent.hasNext()) {
	      String[] nameValPair = (String[])(iterContent.next());
	      if( nameValPair[0] == selectedOID ) {
	        checkFlag = checkedStr;
	      }
	      
	      if(i%2==0)
		  	listID = "listOdd";
		  else
		    listID = "listEven";		  

		  String javascriptStr = fixSingleQuote(nameValPair[1]);
	    %>
	    <tr class="<%=listID%>">
	      <td headers="select" width="10%" valign="top" align="center" id="<%=nameValPair[0]%>"> 
	        <input type="radio" <%=checkFlag%> name="OIDSelection" onClick="onSelect('<%=nameValPair[0]%>', '<%=javascriptStr%>')">
	      </td>
	      <td headers="name" width="90%" valign="top" id="<%=nameValPair[0]%>">
	        <%=nameValPair[1]%>1111
	      </td>
	    </tr>
	    <%
	      i++;
	    }
	    %>
	  </table>
	    
      <div class="pageButtonWrap" align="right">
          <input type="submit" name="cancel" class="pageButton" 
             value="<bean:message bundle="appCommonRes" key="button.can"/>" onClick="JavaScript:window.close()"/>
          <input type="submit" name="save" class="pageButton" 
             value="<bean:message bundle="appCommonRes" key="button.sav"/>" onClick="JavaScript:onSave()"/>
	    </div>   
     </div>
  
    </form>

  </body>
</html>
